{extend name="layout/iframe" /}

{block name="pagecss"}
<style>
    .layui-form-radio {
        margin: -3px 10px 0 0;
    }
    /*#Images li .operate .img_del {
        margin: -2px -28px 0 0;
    }*/
</style>
{/block}

{block name="content"}
<form class="layui-form">
    <blockquote class="layui-elem-quote news_search">
        <!--<div class="layui-inline">
            <input type="checkbox" name="selectAll" id="selectAll" lay-filter="selectAll" lay-skin="primary" title="全选">
        </div>
        <div class="layui-inline">
            <a class="layui-btn layui-btn-sm layui-btn-danger batchDel">批量删除</a>
        </div>-->
        <div class="layui-inline" id="upload-image">
            <a class="layui-btn layui-btn-sm upload-file" id="upload-btn" data-multi="false">上传图片</a>
        </div>
    </blockquote>

    <ul class="layer-photos-demo" id="Images">
        <!--<li>
            <a href="" target="_blank">
                <img src="" alt="" style="height: 204px;">
            </a>
            <div class="operate">
                <div class="check">
                    <input type="radio" name="cover" value="" lay-filter="choose" title="设为封面" checked="">
                    <div class="layui-unselect layui-form-radio layui-form-radioed"><i class="layui-anim layui-icon"></i><div>设为封面</div></div>
                </div>
                <i class="layui-icon img_del"></i>
            </div>
        </li>-->
    </ul>
</form>

<input type="hidden" class="datalist_url" value="{:url('admin/product/getimgurls')}">
{/block}

{block name="pagescript"}
<script src="__STATIC__/admin/js/qiniu/plupload.full.min.js" type="text/javascript"></script>
<script src="__STATIC__/admin/js/qiniu/qiniu.js" type="text/javascript"></script>
<script src="__STATIC__/admin/js/qiniu/qiniuConfig.js" type="text/javascript"></script>

<script type="text/javascript">
    layui.use(['form', 'layer'], function(){

        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : top.layer,
            $ = layui.jquery;


        var datalist_url = $('.datalist_url').val();


        /*if ($(parent.window.frames[0].document).find('input[name=id]').val()) {
            datalist_url += '?id=' + $(parent.window.frames[0].document).find('input[name=id]').val();
        } else {
            datalist_url += '?img_urls=' + $(parent.window.frames[0].document).find('.img_urls').val();
        }*/
        datalist_url += '?img_urls=' + $(parent.window.frames[0].document).find('.img_urls').val();
        function ajaxDatatable() {
            $.post(
                datalist_url,
                function(res){
                    // 插入数据
                    var imgList = [],
                        data = res.data;
                    var length = data.length;
                    setTimeout(function(){
                        for(var i = 0; i < length; i++){
                            var checked = '';
                            var cover_img = $(parent.window.frames[0].document).find('.img_url').val();
                            if(cover_img && cover_img == data[i].img_url){
                                checked = 'checked';
                                // 设为封面
                                $(parent.window.frames[0].document).find('.img_url').val(data[i].img_url);
                                $(parent.window.frames[0].document).find('.default_upload').attr('src', data[i].img_url);
                            }
                            var html = '';
                            html += '<li class="layer-img">';
                                html += '<a href="'+ data[i].img_url +'" target="_blank"><img src="'+ data[i].img_url +'" alt="图片" ></a>';
                                html += '<div class="operate">';
                                html += '<div class="check"><input type="radio" name="img" value="'+ data[i].img_url +'" lay-filter="choose" lay-skin="primary" title="设为封面" '+ checked +'><div class="layui-unselect layui-form-radio layui-form-radioed"><i class="layui-anim layui-icon"></i><div>设为封面</div></div>';
                                //html += '<i class="layui-icon img_del" style="margin: -2px -28px 0 0;">&#xe640;</i>';
                                if (checked) {
                                    html += '<i class="layui-icon img_del" style="display: none;margin: -2px -28px 0 0;">&#xe640;</i>';
                                } else {
                                    html += '<i class="layui-icon img_del" style="margin: -2px -28px 0 0;">&#xe640;</i>';
                                }
                                html += '</div>';
                            html += '</li>';
                            imgList.push(html);
                        }
                        $('#Images').append(imgList);

                        // 设置图片的高度
                        $("#Images li img").height($("#Images li img").width());
                        form.render();
                    }, 500);
                }
            );
        }
        ajaxDatatable();

        // 选择封面
        $('#Images').on('click', '.layui-form-radio', function () {
            var value = $(this).parent().find('input[type=radio]').val();
            $(parent.window.frames[0].document).find('.img_url').val(value);
            $(parent.window.frames[0].document).find('.default_upload').attr('src', value);

            $('#Images').find('.img_del').css('display', 'block');
            $(this).parent().find('.img_del').css('display', 'none');
        });

        var UploadFile = function() {

            var upload_element = 'upload-image'; // 上传按钮的上级元素ID
            var upload_btn = 'upload-btn'; // 上传按钮的ID
            var field = $('#' + upload_btn).attr('data-field');
            var token_url = $('.token_url').val();
            var record_url = $('.record_url').val();
            var max_file_size = $('#' + upload_btn).attr('data-max_file_size');
            var extensions = $('#' + upload_btn).attr('data-extensions');
            var multi = $('#' + upload_btn).attr('data-multi');
            var isAjax = $('#' + upload_btn).attr('data-ajax');


            /**
             * 七牛初始化
             */
            var initUploader = function () {
                var url = "";
                var qiniupercent = "";
                var uploader = upload_element;
                var pickfiles = upload_btn;

                if($('#' + uploader).length <= 0){
                    return;
                }

                if(extensions == '' || extensions == undefined){
                    extensions = 'jpg,jpeg,gif,png';
                }
                if(multi == 'false'){
                    multi = false;
                    if(max_file_size == '' || max_file_size == undefined){
                        max_file_size = '500kb';
                    }
                }else{
                    multi = true;
                    if(max_file_size == '' || max_file_size == undefined){
                        max_file_size = '1MB';
                    }
                }
                if(isAjax == 'true'){
                    isAjax = true;
                }else{
                    isAjax = false;
                }

                $.ajax({
                    url: token_url,
                    type: 'POST',
                    data: {},
                    cache: false,
                    contentType: false,    //不可缺
                    processData: false,    //不可缺
                    dataType : 'json',
                    success: function (data) {
                        uploaderReadyForImg(data.uptoken, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi);
                    }
                });
            };

            var uploaderReadyForImg = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
                var uploaderForUditor = Qiniu.uploader({
                    runtimes: 'html5,flash,html4',
                    browse_button: pickfiles,     //上传按钮的ID
                    container: uploader,      //上传按钮的上级元素ID
                    drop_element: uploader,
                    max_file_size: max_file_size,         //最大文件限制
                    flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
                    dragdrop: false,
                    chunk_size: '4mb',              //分块大小
                    //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
                    uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
                    // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
                    domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
                    multi_selection: multi,         //是否允许同时选择多文件
                    filters: {
                        mime_types: [               //文件类型过滤，这里限制为图片类型
                            {title: "Image files", extensions: extensions}
                        ]
                    },
                    auto_start: true,
                    unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
                    init: {
                        'FilesAdded': function (up, files) {
                            plupload.each(files, function(file) {
                                // 文件添加进队列后，处理相关的事情
                                if(typeof TOTAL_IMG != 'undefined') {
                                    if (COUNT_IMG >= TOTAL_IMG) {
                                        layer.msg('最多上传' + TOTAL_IMG + '张');
                                        up.removeFile(file);
                                        return;
                                    }
                                    COUNT_IMG ++;
                                    console.log('增加到：' + COUNT_IMG);
                                }
                            });
                        },
                        'BeforeUpload': function (up, file) {
                            // 每个文件上传前，处理相关的事情
                            layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                        },
                        'UploadProgress': function (up, file) {
                            //文件上传时，处理相关的事情

                            //上传进度 class="layui-btn" type="button"

                            //console.log(file.percent + "%");
                        },
                        'UploadComplete': function () {
                            //do something
                        },
                        'FileUploaded': function (up, file, info) {
                            //每个文件上传成功后,处理相关的事情,并记录到数据库
                            //其中 info 是文件上传成功后，服务端返回的json，形式如
                            //{
                            //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                            //  "key": "gogopher.jpg"
                            //}
                            var domain = up.getOption('domain');
                            var res = eval('(' + info.response + ')');
                            var sourceLink = domain + res.key;//获取上传文件的链接地址
                            //console.log(sourceLink);
                            $.ajax({
                                url: record_url,
                                type: 'POST',
                                data: {
                                    'imgUrl': sourceLink
                                },
                                cache: false,
                                dataType: 'json',
                                success: function (data) {
                                    layer.closeAll('loading'); // 关闭loading
                                    if (data.code === '1') {
                                        if(multi) {  // 多图
                                            //
                                        } else {
                                            // 单图
                                            var checked = '';
                                            if($('#Images').find('li').length <= 0){
                                                checked = 'checked';
                                                // 设为封面
                                                $(parent.window.frames[0].document).find('.img_url').val(sourceLink);
                                                $(parent.window.frames[0].document).find('.default_upload').attr('src', sourceLink);
                                            }
                                            var html = '';
                                            html += '<li class="layer-img">';
                                                html += '<a href="'+ sourceLink +'" target="_blank"><img src="'+ sourceLink +'" alt="图片" ></a>';
                                                html += '<div class="operate">';
                                                    html += '<div class="check"><input type="radio" name="img" value="'+ sourceLink +'" lay-filter="choose" lay-skin="primary" title="设为封面" '+ checked +'></div>';
                                                    //html += '<i class="layui-icon img_del">&#xe640;</i>';
                                                    if (checked) {
                                                        html += '<i class="layui-icon img_del" style="display: none;">&#xe640;</i>';
                                                    } else {
                                                        html += '<i class="layui-icon img_del">&#xe640;</i>';
                                                    }
                                                html += '</div>';
                                            html += '</li>';

                                            $('#Images').append(html);
                                            // 设置图片的高度
                                            $("#Images li img").height($("#Images li img").width());
                                            form.render("radio");

                                            // 添加图片
                                            var img_urls_elm = $(parent.window.frames[0].document).find('.img_urls');
                                            var img_urls = img_urls_elm.val();
                                            if(img_urls){
                                                img_urls = img_urls + ',' + sourceLink;
                                            }else{
                                                img_urls = sourceLink;
                                            }

                                            img_urls_elm.val(img_urls);
                                        }
                                    }
                                }
                            });

                        },
                        'Error': function (up, err, errTip) {
                            layer.closeAll('loading'); // 关闭loading
                            alert(errTip);
                        },
                    }
                });
            };


            return {
                init: function() {
                    initUploader();
                }

            };

        }();

        UploadFile.init();


        /**
         * 删除图片
         * 删除记录数据及七牛空间中的图片
         */
        $(document).find('#Images').on('click', '.img_del', function(){
            var _this = $(this);
            layer.confirm('确定要删除吗？',{icon:3, title:'提示信息'},function(index){
                layer.close(index);

                var img_url = _this.parents('li').find('img').attr('src'); // 图片地址
                var element = _this.parents('li'); // 要删除元素
                var delimage_url = $('.delimage_url').val();

                $.ajax({
                    url: delimage_url,
                    type: 'POST',
                    data: {
                        'imgUrl' : img_url,
                    },
                    cache: false,
                    dataType : 'json',
                    success: function (data) {
                        if(data.code === '1') {
                            element.hide(1000);
                            setTimeout(function(){element.remove();},950);
                            layer.msg('删除成功');
                            if(typeof TOTAL_IMG != 'undefined') {
                                COUNT_IMG --;
                                console.log('减少到:' + COUNT_IMG);
                            }

                            // 删除图片
                            var img_urls_elm = $(parent.window.frames[0].document).find('.img_urls');
                            var img_urls = img_urls_elm.val();
                            var arr = img_urls.split(',');
                            var new_img_urls = '';
                            for(var i = 0; i < arr.length; i++){
                                if(arr[i] != img_url){
                                    new_img_urls += ',' + arr[i];
                                }
                            }

                            img_urls_elm.val(new_img_urls.substr(1));
                        } else{
                            layer.msg('删除失败');
                        }
                    }
                });
            });
        });
    });
</script>
{/block}